package com.powernode.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.powernode.config.AliyunSmsConfig;
import com.powernode.constant.MemberConstants;
import com.powernode.domain.Member;
import com.powernode.ex.handler.BusinessException;
import com.powernode.service.AliyunSmsService;
import com.powernode.service.MemberService;
import com.powernode.util.AuthUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Duration;
import java.util.Map;

/**
 * @create: 2024/7/24
 * @author: gyhe10
 * @description:
 **/

@Service
public class AliyunSmsServiceImpl implements AliyunSmsService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private AliyunSmsConfig aliyunSmsConfig;
    @Resource
    private MemberService memberService;

    /**
     * 发送短信验证码
     *
     * @param map
     */
    @Override
    public void sendPhoneCode(Map<String, Object> map) {

        // 准备配置对象
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                .setAccessKeyId(aliyunSmsConfig.getAccessKeyId())
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                .setAccessKeySecret(aliyunSmsConfig.getAccessKeySecret());
        // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
        config.endpoint = aliyunSmsConfig.getEndpoint();
        try {
            // 创建客户端对象
            com.aliyun.dysmsapi20170525.Client client = new com.aliyun.dysmsapi20170525.Client(config);
            // 创建请求参数对象
            // 必填，短信接收号码
            String phoneNumber = (String) map.get("phonenum");

            // 生成随机数字验证码
            String randomNumber = RandomUtil.randomNumbers(4);
            // 将生成的验证码保存到redis中
            stringRedisTemplate.opsForValue().set(MemberConstants.PHONE_CODE_KEY_PREFIX + phoneNumber, randomNumber, Duration.ofMinutes(30));
            // 必填，模板参数
            String templateParam = "{\"code\":\""+ randomNumber +"\"}";
            com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                    .setPhoneNumbers(phoneNumber)
                    .setSignName(aliyunSmsConfig.getSignName())
                    .setTemplateCode(aliyunSmsConfig.getTemplateCode())
                    .setTemplateParam(templateParam);
            // 发送请求
            client.sendSmsWithOptions(sendSmsRequest, new com.aliyun.teautil.models.RuntimeOptions());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 绑定用户手机号
     *
     * @param map
     * @return
     */
    @Override
    public Boolean savePhone(Map<String, String> map) {
        // 获取用户输入的验证码
        String inputCode = map.get("code");
        // 获取用户手机号
        String phoneNumber = map.get("phonenum");
        // 从redis中获取当前手机号对应的验证码
        String redisCode = stringRedisTemplate.opsForValue().get(MemberConstants.PHONE_CODE_KEY_PREFIX + phoneNumber);
        // 判断验证码是否正确
        if (!inputCode.equals(redisCode)) {
            throw new BusinessException("验证码错误，请输入正确的验证码");
        }
        // 验证码正确，保存手机号
        // 获取当前用户的openId
        String openId = AuthUtils.getMemberOpenId();
        Member member = new Member();
        member.setUserMobile(phoneNumber);
        member.setOpenId(openId);

        return memberService.update(member, new LambdaQueryWrapper<Member>()
                .eq(Member::getOpenId, openId));
    }
}
